package com.example.demo.service;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.UUID;

@Service
public class CozeApiService {

    private static final String COZE_API_URL = "https://api.coze.cn/open_api/v3/chat";
    private static final String TOKEN = "pat_vFIodd1YKh1ExBMW849gJF2BdtFJ3JBMl8mR2PxxgSrf8xwTnEp39GOtVSGwSrsc" ;  // Coze平台的token
    private static final String BOT_ID = "7411412336043114523";  // Coze平台的bot_id

    // 调用 Coze API 获取 AI 生成的回答
    public String cozeChat(String query) throws Exception {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer" + TOKEN);
        headers.set("Content-Type", "application/json");
//        headers.set("Accept", "application/json");

        // 构建请求数据
        String userId = UUID.randomUUID().toString();
                String requestBody = String.format(
                "{\"bot_id\":\"%s\", \"user_id\":\"%s\", \"stream\":false, \"auto_save_history\":true, \"additional_messages\":[{\"role\":\"user\", \"content\":\"%s\", \"content_type\":\"text\"}]}",
                BOT_ID, userId, query
        );

        HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);

        // 发送请求
        ResponseEntity<String> response = restTemplate.exchange(COZE_API_URL, HttpMethod.POST, entity, String.class);

        // 处理响应
        System.out.println(response.getBody());
        return extractAnswers(response.getBody());
    }

    // 提取响应中的回答内容
    private String extractAnswers(String response) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode root = mapper.readTree(response);
        StringBuilder answers = new StringBuilder();

        for (JsonNode message : root.path("messages")) {
            if ("answer".equals(message.path("role").asText())) {
                answers.append(message.path("content").asText());
            }
        }

        return answers.toString();
    }
}
